package com.nj.dms.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//数据库连接以及关闭等方法
public class DbUtil {

	private static String driver;
	private static String url;
	private static String dbUser;
	private static String dbPassword;
	// staic修饰的语句块只加载一次
	static {
		driver = "com.mysql.jdbc.Driver";
		// 数据库增删改时支持汉字
		// useUnicode=true
		// characterEncoding=utf-8
		url = "jdbc:mysql://localhost:3306/nj_dms?useUnicode=true&characterEncoding=utf-8";
		dbUser = "root";
		dbPassword = "root";
	}

	// 获取数据库连接对象
	public static Connection dbOpen() {
		Connection conn = null;

		try {
			// 动态加载mysql的驱动类
			Class.forName(driver);

			// 获得Connection连接对象
			conn = (Connection) DriverManager.getConnection(url, dbUser, dbPassword);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	// 关闭当前打开的数据库连接Statement对象
	public static void dbClose(Connection conn, Statement stmt) {
		try {
			// 先关闭Statement对象
			if (stmt != null) {
				stmt.close();
			}
			// 再关闭Connection对象
			if (conn != null) {
				conn.close();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 关闭当前打开的数据库连接 PreparedStatement对象
	public static void dbClose(Connection conn, PreparedStatement pstmt) {
		try {
			if (pstmt != null) {
				pstmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 关闭当前打开的数据库连接PreparedStatement对象 ResultSet对象
	public static void dbClose(Connection conn, PreparedStatement pstmt, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (pstmt != null) {
				pstmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
